<script>
  import { prepareWorld } from './index';
  import { listSaves } from '$lib/browserdb';
  import { worldFromObject } from '$lib/serialize';
  import Game from './Game.svelte';

  let autoload = $state(false);
  const games = listSaves();
  let game = $state(undefined);

  const selectSave = (save) => {
    const world = worldFromObject(JSON.parse(save.content));
    game = (...args) => Game(args[0], { world });
  };

  const newGame = () => {
    const world = prepareWorld();
    game = (...args) => Game(args[0], { world });
  };
</script>

<section>
  {#if game}
    <svelte:component this={game} />
  {:else}
    <span onclick={newGame}>New game</span>
    <p>Load</p>
    {#await games}
      ...loading...
    {:then result}
      <ul>
        {#each result as game}
          <li onclick={() => selectSave(game)}>{game.name}</li>
        {/each}
      </ul>
    {:catch err}
      {err}
    {/await}
  {/if}
</section>
